# -*- coding:utf-8 -*-
from .models import db, Student
from application import redis_store
import random
import json
from flask import request
from application.utils.constant import CONSTANT


# import logging

# log = logging.getLogger("home")


def index():
    # # mysql 使用
    # # 新增数据
    # student = Student(name="xsk", avatar="1.png", age=16, sex=True, money=1000)
    # db.session.add(student)
    # db.session.commit()

    # # 查询指定id的数据
    # query = Student.query.filter(Student.id==2).first()
    # data = query.__to_dict__(["id","name","avatar","age","sex","money"])
    # print data

    # 查询所有数据对象
    # student_list = Student.query.filter(Student.is_deleted==False).all()
    # student_list = Student.query.all()
    # datas = []
    # for student in student_list:
    #      # 因为money是浮点数类型，因此不能直接转为字典，需要解析后才能用
    #     item = student.__to_dict__(["id","name","avatar","age","sex","money"])
    #     datas.append(item)
    # print type(data)
    student_list = Student.query.filter(Student.is_deleted == False).all()
    print(student_list)
    data_list = []
    for student in student_list:
        data_dict = {}
        name = student.name
        age = student.age
        sex = student.sex
        money = student.money
        data_dict["name"] = name
        data_dict["age"] = age
        data_dict["sex"] = sex
        # data_dict["money"] = "%.2f" % money
        data_dict["money"] = "{:.2f}".format(money)
        data_list.append(data_dict)
    print(data_list)
    data = {"code": 0, "msg": "success", "data": data_list}
    return data


def redis_demo():
    result = {
        "msg": "failed",
        "code": 1,
        "data": {}
    }
    tel = "15768816912"

    # 获取请求类型
    method_type = request.method
    if method_type == "POST":
        # 获取随机4位数，不足的以0补足
        random_num = "%04d" % random.randint(0, 9999)

        # 调用redis
        # 第一个参数是key，第二个参数是value，第三个参数是过期时间60秒
        redis_res = redis_store.set("tel_{}".format(tel), random_num, 60)
        print(random_num)
        if redis_res:
            result["msg"] = "success"
            result["code"] = 0
            result["data"].update({"tel": tel, "value": random_num})
        # log.info("test_print_info")

    elif method_type == "GET":
        # 判断key是否存在,存在则为False 不设置，不存在则为True 设置默认值  name, value
        redis_store.setnx("tel_{}".format(tel), "1")
        res = redis_store.get("tel_{}".format(tel))
        print(res)
        if res == '1':
            result["msg"] = "数据已过期或没有该数据"
            return result

        print("随机四位数为：{}".format(res))
        result["msg"] = "success"
        result["code"] = 0
        result["data"].update({"tel": tel, "value": res})
    else:
        result["msg"] = "没有这种方法，请确认方法是否正确"

    return result


def student_info():
    result = {
        "msg": "failed",
        "code": 1,
        "data": []
    }
    # 获取请求类型
    method_type = request.method

    # 增
    if method_type == "POST":
        # 获取body里面的data数据
        all_data = request.data
        print(all_data, type(all_data))
        if not all_data:
            result["msg"] = "传入参数不能为空"
            return result

        all_data = json.loads(all_data)
        name = all_data.get("name", "")
        age = all_data.get("age", 0)
        money = all_data.get("money", 0)
        avatar = all_data.get("avatar", "")
        sex = all_data.get("sex", False)

        if not all([name, age]):
            result["msg"] = "请传入正确的参数"
            return result

        student = Student(name=name, age=age, money=money, sex=sex, avatar=avatar)
        print(student)
        if not student:
            result["msg"] = "无该数据，无法修改"
            return result
        db.session.add(student)
        db.session.commit()

        datas = list()
        data = dict()
        user_id = student.id
        name = student.name
        age = student.age
        sex = student.sex
        money = student.money
        data["id"] = user_id
        data["name"] = name
        data["age"] = age
        data["sex"] = sex
        data["money"] = "{:.2f}".format(money)
        datas.append(data)

        result["msg"] = "success"
        result["code"] = 0
        result["data"] = datas

    # 查
    elif method_type == "GET":
        # 获取url里面的参数   to_dict() 转换 ImmutableMultiDict 类型为字典类型v
        all_data = request.args.to_dict()
        print(all_data)
        if not all_data:
            # student_list = Student.query.filter(Student.is_deleted == False).all()
            # 降序
            # student_list = Student.query.filter(Student.is_deleted == False).order_by(db.desc(Student.create_time)).all()
            # 升序
            student_list = Student.query.filter(Student.is_deleted == False).order_by(Student.create_time).all()

        else:
            user_id = all_data.get("id", None)
            # student_list = Student.query.filter(Student.is_deleted == False, Student.id == user_id).first()
            student_list = Student.query.filter(Student.is_deleted == False, Student.id == user_id).order_by(
                Student.create_time)
        # 根据is_deleted获取数据

        print(student_list)
        if not student_list:
            result["msg"] = "无法查询到对应的数据，请确认参数是否正确"
            return result

        datas = list()
        for student in student_list:
            data = dict()
            user_id = student.id
            name = student.name
            age = student.age
            sex = student.sex
            money = student.money
            data["id"] = user_id
            data["name"] = name
            data["age"] = age
            data["sex"] = sex
            data["money"] = "{:.2f}".format(money)
            datas.append(data)
        result["msg"] = "success"
        result["code"] = 0
        result["data"] = datas

    # 修改put
    elif method_type == "PUT":
        # 获取body里面的data数据
        all_data = request.data
        print(all_data, type(all_data))
        if not all_data:
            result["msg"] = "传入参数不能为空"
            return result

        all_data = json.loads(all_data)
        user_id = all_data.get("id", None)
        name = all_data.get("name", None)
        age = all_data.get("age", None)

        if not all([user_id, name, age]):
            result["msg"] = "请传入正确的参数"
            return result

        student = Student.query.filter(Student.id == user_id, Student.is_deleted == False).update(all_data)
        print(student)
        if not student:
            result["msg"] = "无该数据，无法修改"
            return result

        db.session.commit()
        # print("数据修改成功")

        result["msg"] = "success"
        result["code"] = 0
        result["data"] = {}

    # 逻辑删除
    elif method_type == "DELETE":
        # 获取body里面的data数据
        all_data = request.data
        print(all_data, type(all_data))
        if not all_data:
            result["msg"] = "传入参数不能为空"
            return result

        all_data = json.loads(all_data)
        user_id = all_data.get("id", None)

        if not all([user_id]):
            result["msg"] = "请传入正确的参数"
            return result

        student = Student.query.filter(Student.id == user_id).update({"is_deleted": True})
        print(student)
        if not student:
            result["msg"] = "无该数据，无法删除"
            return result
        db.session.commit()

        result["msg"] = "success"
        result["code"] = 0
        result["data"] = {}

    else:
        result["msg"] = "error"

    return result
